/*
 * DDS Sine Generator mit ATMEGS 168
 * Timer2 generates the  31250 KHz Clock Interrupt
 *
 * KHM 2009 /  Martin Nawrath
 * Kunsthochschule fuer Medien Koeln
 * Academy of Media Arts Cologne
 * http://interface.khm.de/index.php/lab/experiments/arduino-dds-sinewave-generator/
 */

//========================================================   
// CIC filter
// N=2, R=8, M=1   
// -- N=order=2 (2 integrators, 2 comb filters)
// -- R=upsample=8 
// -- M=delay(before upsample)=1
// Bits required is Bout = N*log2(RM) + Bin
// or 2*log2(8)+8=2*3+8=14, so 16 bit longs should be fine
// Bruce Land -- Cornell University -- March 2010
// see also
// http://www.mikrocontroller.net/attachment/51932/cic2.pdf
// http://www.altera.com/literature/an/an455.pdf
// https://instruct1.cit.cornell.edu/courses/ee476/Math/GCC644/CICfilters/CIC_filter_N2_R4_M2.c

#include "avr/pgmspace.h"

#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

// table of 256 sine values / one sine period / stored in flash memory
PROGMEM  prog_uchar sine256[]  = {
  127,130,133,136,139,143,146,149,152,155,158,161,164,167,170,173,176,178,181,184,187,190,192,195,198,200,203,205,208,210,212,215,217,219,221,223,225,227,229,231,233,234,236,238,239,240,
  242,243,244,245,247,248,249,249,250,251,252,252,253,253,253,254,254,254,254,254,254,254,253,253,253,252,252,251,250,249,249,248,247,245,244,243,242,240,239,238,236,234,233,231,229,227,225,223,
  221,219,217,215,212,210,208,205,203,200,198,195,192,190,187,184,181,178,176,173,170,167,164,161,158,155,152,149,146,143,139,136,133,130,127,124,121,118,115,111,108,105,102,99,96,93,90,87,84,81,78,
  76,73,70,67,64,62,59,56,54,51,49,46,44,42,39,37,35,33,31,29,27,25,23,21,20,18,16,15,14,12,11,10,9,7,6,5,5,4,3,2,2,1,1,1,0,0,0,0,0,0,0,1,1,1,2,2,3,4,5,5,6,7,9,10,11,12,14,15,16,18,20,21,23,25,27,29,31,
  33,35,37,39,42,44,46,49,51,54,56,59,62,64,67,70,73,76,78,81,84,87,90,93,96,99,102,105,108,111,115,118,121,124

};

int testPin = 7;
int t2Pin = 6;
byte bb;

double dfreq;
// const double refclk=31372.549;  // =16MHz / 510
const double refclk=31376.6;      // measured

// variables used inside interrupt service declared as voilatile
volatile byte icnt;              // var inside interrupt
volatile byte icnt1;             // var inside interrupt
volatile byte c4ms;              // counter incremented all 4ms
volatile unsigned long phaccu;   // pahse accumulator
volatile unsigned long tword_m;  // dds tuning word m

void setup() { 
 //Initialize serial and wait for port to open:
  Serial.begin(9600);
  pinMode(7, OUTPUT);
  pinMode(11, OUTPUT);     // pin11= PWM  output / frequency output
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  } 

  Setup_timer2();

  // disable interrupts to avoid timing distortion
  cbi (TIMSK0,TOIE0);              // disable Timer0 !!! delay() is now not available
  sbi (TIMSK2,TOIE2);              // enable Timer2 Interrupt

  dfreq=1000.0;                    // initial output frequency = 1000.o Hz
  tword_m=pow(2,32)*dfreq/refclk;  // calulate DDS new tuning word 
} 

void loop()
{
}

//CIC-filter implementation:
//N=2
//R= variable, depending on how many times bNewSample is set to true
//M=1
//This function takes about 10us to execute = 160 clock cycles.
byte CIC_n2_r8_m1(byte ySampleIn, boolean bNewSample)
{
    static int comb1, comb2, integrator1, integrator2, comb2Out;
    int comb1Out=0;
    int iSampleIn=ySampleIn;

    if(bNewSample)
    {
        //Input data should be symmetrical around 0, otherwise the
        //integrators will keep increasing.  Eventually overflow will
        //occur, but that might take some time.
        //So adding a -128 offset.
        iSampleIn=((int)ySampleIn)-128;
        //modulo 8: 2 comb filters run at original, slow datarate
        comb1Out=iSampleIn-comb1;
        comb2Out=comb1Out-comb2;

        //Update registers
        comb1=iSampleIn;
        comb2=comb1Out;
        iSampleIn=comb2Out;
    }

    //integrators runs at upsampled datarate
    integrator1=iSampleIn+integrator1;
    integrator2=integrator1+integrator2;

    //Removing the offset again.
    return (integrator2>>3)+128;
}

//******************************************************************
// timer2 setup
// set prscaler to 1, PWM mode to phase correct PWM,  16000000/510 = 31372.55 Hz clock
void Setup_timer2() {

// Timer2 Clock Prescaler to : 1
  sbi (TCCR2B, CS20);
  cbi (TCCR2B, CS21);
  cbi (TCCR2B, CS22);

  // Timer2 PWM Mode set to Phase Correct PWM
  cbi (TCCR2A, COM2A0);  // clear Compare Match
  sbi (TCCR2A, COM2A1);

  sbi (TCCR2A, WGM20);  // Mode 1  / Phase Correct PWM
  cbi (TCCR2A, WGM21);
  cbi (TCCR2B, WGM22);
}

//******************************************************************
// Timer2 Interrupt Service at 31372,550 KHz = 32uSec
// this is the timebase REFCLOCK for the DDS generator
// FOUT = (M (REFCLK)) / (2 exp 32)
// runtime : 8 microseconds ( inclusive push and pop)
ISR(TIMER2_OVF_vect) {
  static byte upSampleClock=0;
  sbi(PORTD,7);          // Test / set PORTD,7 high to observe timing with a oscope

  phaccu=phaccu+tword_m; // soft DDS, phase accu with 32 bits
  icnt=phaccu >> 24;     // use upper 8 bits for phase accu as frequency information
                         // read value fron ROM sine table and send to PWM DAC
  if((upSampleClock & 0x3)==0){       
    OCR2A=CIC_n2_r8_m1(pgm_read_byte_near(sine256 + icnt),true);    
  }else{
    OCR2A=CIC_n2_r8_m1(0,false);
  }

//  if((upSampleClock & 0x3)==0){       
//    OCR2A=pgm_read_byte_near(sine256 + icnt);    
//  };

  upSampleClock++;
 cbi(PORTD,7);            // reset PORTD,7
}
 

